/*
 * CellFireController.cc
 *
 * @created Apr 11, 2013
 * @author Tim Niggemann, III Phys. Inst. A, RWTH Aachen University
 * @copyright GNU General Public License v3.0
 */

#include "digi/G4SipmCellFireController.hh"

#include "G4SipmUiMessenger.hh"
// 构造函数用于初始化G4SipmCellFireController对象，接受一个SiPM模型和初始时间戳作为参数。
G4SipmCellFireController::G4SipmCellFireController(G4SipmModel *sipmModel, double t0) : model(sipmModel)
{
	// 获取SiPM模型中总的单元数，并为每个单元初始化时间戳
	unsigned int nCells = model->getNumberOfCells();
	for (unsigned int i = 0; i < nCells; i++)
	{
		cellIdToTimeMap[i] = t0;
	}
	// 刷新模型的增益映射
	model->getGainMapModel()->refresh(model);
}
// 析构函数，用于销毁G4SipmCellFireController对象
G4SipmCellFireController::~G4SipmCellFireController()
{
	cellIdToTimeMap.clear();
}
// 触发硅光电倍增管（SiPM）单元，并根据触发时间更新其权重和时间戳。返回一个布尔值，表示是否成功触发。
bool G4SipmCellFireController::fire(G4SipmDigi *d)
{
	double &cellTime = cellIdToTimeMap[d->getCellId()];
	// Check timing.
	// 检查触发时间是否满足条件，包括死时间和单元编号的有效性。如果过滤定时器被激活，则进一步检查权重是否大于0。
	if (G4SipmUiMessenger::getInstance()->isFilterTiming())
	{
		if (cellTime + model->getDeadTime() >= d->getTime() || d->getCellId() >= model->getNumberOfCells() || d->getWeight() <= 0.)
		{
			return false;
		}
	}
	// Determine gain from the recovery behaviour of the capacitor in the diode equivalent circuit.
	// 计算增益，考虑到电容在二极管等效电路中的恢复行为。
	double gain = 1. - exp(-(d->getTime() - cellTime - model->getDeadTime()) / model->getRecoveryTime());
	// Update weight of the digi.
	// 更新数字信号的权重，考虑到增益和SiPM单元的初始增益。
	d->setWeight(gain * model->getGain(d->getCellId()));
	// Update time.
	cellTime = d->getTime();
	// Success.
	return true;
}
